import 'package:dio/dio.dart';
import 'package:network_test/NetWork/NetworkConsts';
import 'package:network_test/NetWork/Result_data.dart';



class HttpManager {
  static HttpManager _instance = HttpManager._internal();
  late Dio _dio;

  ///通用全局单例，第一次使用时初始化
  HttpManager._internal() {
      _dio = new Dio(
          new BaseOptions(baseUrl: BASE_URL, connectTimeout: 15000));
      //_dio.interceptors.add(new DioLogInterceptor());
//      _dio.interceptors.add(new PrettyDioLogger());
      //_dio.interceptors.add(new ResponseInterceptors());
  }

  static HttpManager getInstance() {
      return _instance._defaultSetting();
  }

  HttpManager _defaultSetting() {
    // if (_dio != null) {
    //   if (_dio.options.baseUrl != Address.BASE_URL) {
    //     _dio.options.baseUrl = Address.BASE_URL;
    //   }
    // }
    return this;
  }

  ///通用的GET请求
  get(api, {params, withLoading = true}) async {
    // if (withLoading) {
    //   LoadingUtils.show();
    // }

    Response response;
    try {
      response = await _dio.get(api, queryParameters: params);
      // if (withLoading) {
      //   LoadingUtils.dismiss();
      // }
    } on DioError catch (e) {
      // if (withLoading) {
      //   LoadingUtils.dismiss();
      // }
      return resultError(e);
    }

    if (response.data is DioError) {
      return resultError(response.data['code']);
    }

    return response.data;
  }

}


 ResultData resultError(DioError e) {
  Response errorResponse;
  if (e.response != null) {
    errorResponse = e.response!;
  } else {
    errorResponse = new Response(requestOptions: e.requestOptions, statusCode: 666);
  }
  if (e.type == DioErrorType.connectTimeout ||
      e.type == DioErrorType.receiveTimeout) {
    errorResponse.statusCode = -2;
  }
  return new ResultData(
      errorResponse.statusMessage, false, errorResponse.statusCode ?? 1000);
}
